<template>
  <div class="login">
    <!-- 用于显示名字 -->
    <div class="header">
      <p class="title">灵动教学台</p>
    </div>
    <!-- 内容 -->
    <div class="content">
      <!-- 放图片 -->
      <div class="content-left">
        <img src="../../static/logo.jpg" class="img-bg">
      </div>
      <!-- 放表单 -->
      <div class="content-right">
        <!-- 登录 -->
        <div class="content-right-title">登录</div>
        <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px"
          class="demo-ruleForm myform">

          <el-form-item label="用户名" prop="username">
            <el-input v-model.number="ruleForm.username" placeholder="请输入用户名"></el-input>
          </el-form-item>

          <el-form-item label="密码" prop="pass">
            <el-input type="password" v-model="ruleForm.pass" autocomplete="off" placeholder="请输入密码"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="toHome" :plain="true">登录</el-button>
            <el-button @click="toRejister">注册</el-button>
          </el-form-item>

        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import {
  mapState
} from 'vuex'
export default {
  data () {
    const checkUsername = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('用户名不能为空'))
      }
    }
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass')
        }
        callback()
      }
    }
    return {
      fullWidth: document.documentElement.clientWidth,
      fullHeight: document.documentElement.clientHeight,
      ruleForm: {
        pass: '',
        username: ''
      },
      rules: {
        pass: [{
          validator: validatePass,
          trigger: 'blur'
        }],
        username: [{
          validator: checkUsername,
          trigger: 'blur'
        }]
      }
    }
  },
  computed: {
    ...mapState
  },
  mounted () {
    /* 页面挂载获取cookie，如果存在username的cookie，则跳转到主页，不需登录 */
    if (this.getCookie('username')) {
      this.$router.push('/home')
    }
  },
  methods: {
    setCookie (cname, value, expire) {
      const date = new Date()
      date.setSeconds(date.getSeconds() + expire)
      document.cookie = cname + '=' + escape(value) + '; expires=' + date.toGMTString()
      console.log(document.cookie)
    },
    getCookie (cname) {
      if (document.cookie.length > 0) {
        let cstart = document.cookie.indexOf(cname + '=')
        if (cstart !== -1) {
          cstart = cstart + cname.length + 1
          let cend = document.cookie.indexOf(';', cstart)
          if (cend === -1) cend = document.cookie.length
          return unescape(document.cookie.substring(cstart, cend))
        }
      }
      return ''
    },
    delCookie (cname) {
      this.setCookie(cname, '', -1)
    },
    handleResize () {
      this.fullWidth = document.documentElement.clientWidth
      this.fullHeight = document.documentElement.clientHeight
    },
    toRejister () {
      this.$router.push('/register')
    },
    async toHome () {
      console.log(this.ruleForm.username)
      console.log(this.ruleForm.pass)
      if (this.ruleForm.username && this.ruleForm.pass) {
        const res = await axios.get('http://127.0.0.1:8000/api/login_app/login/', {
          params: {
            username: this.ruleForm.username,
            password: this.ruleForm.pass
          }
        })
        if (res.data.msg.status === true) {
          console.log(res)
          this.$store.state.name = this.ruleForm.username
          localStorage.setItem('username', this.ruleForm.username)
          this.setCookie('username', this.ruleForm.username, 1000 * 60 * 60 * 24 * 7)
          this.$message({
            message: '登录成功',
            type: 'success'
          })
          this.$router.push('/home')
        } else {
          this.$message.error('用户名或密码错误')
        }
      }
    },
    created () {
      window.addEventListener('resize', this.handleResize)
    },
    beforeUnmount () {
      window.removeEventListener('resize', this.handleResize)
    }
  }
}
</script>
